package org.common.netty;

import org.common.utils.ByteUtils;

import java.util.Arrays;

/**
 * 协议Pack编解码器
 */
public class PackCodec {

    /**
     * 解码
     */
    public static Pack decode(byte[] data) {
        int cmdId = ByteUtils.readIntLittleEndian(data, 0);
        byte[] newData = Arrays.copyOfRange(data, 4, data.length);
        return new Pack(cmdId, newData);
    }

    /**
     * 编码
     */
    public static byte[] encode(Pack pack) {
        return encode(pack.getCmdId(), pack.getData());
    }

    /**
     * 编码
     */
    public static byte[] encode(int cmdId, byte[] data) {
        byte[] newData = new byte[4 + data.length];
        ByteUtils.writeIntLittleEndian(newData, 0, cmdId);

        for (int i = 0; i < data.length; i++) {
            newData[4 + i] = data[i];
        }

        return newData;
    }
}
